package com.lingz.manager.modules.minio.util;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }


    /**
     * 默认日期格式
     */
    public static String DEFAULT_FORMAT = "yyyy-MM-dd";

    /**
     * ============================
     * @Author: hanyuhang
     * @Description:
     * @Date:Created: ${DATE}
     * @Modify:
     * =============================
     */
    /**
     * 获取某一年每个月 的时间区间
     */
    public static List<String[]> getMonForYear(String year) throws ParseException {


        List<String> rangeSet = getRangeSet(getCurrYearFirst(Integer.parseInt(year)), getCurrYearLast(Integer.parseInt(year)));
        List<String[]> timeList=new ArrayList<>();
        for (String tt:
                rangeSet) {
            String[] monthTimeInterval = getMonthTimeInterval(tt);
            timeList.add(monthTimeInterval);
        }

        return timeList;
    }

    /**
     *根据时间范围获得月份集
     * @return
     */
    public static List<String> getRangeSet(String beginDate,String endDate){
        /*      Date1.after(Date2),当Date1大于Date2时，返回TRUE，当小于等于时，返回false；
          Date1.before(Date2)，当Date1小于Date2时，返回TRUE，当大于等于时，返回false；
          如果业务数据存在相等的时候，而且相等时也需要做相应的业务判断或处理时，你需要使用：！Date1.after(Date2);*/
        List<String> rangeSet =null;
        SimpleDateFormat sdf = null;
        Date begin_date = null;
        Date end_date = null;
        rangeSet = new ArrayList<String>();
        sdf = new SimpleDateFormat("yyyy-MM");
        try {
            begin_date = sdf.parse(beginDate);//定义起始日期
            end_date = sdf.parse(endDate);//定义结束日期
        } catch (ParseException e) {
            //System.out.println("时间转化异常，请检查你的时间格式是否为yyyy-MM或yyyy-MM-dd");
        }
        Calendar dd = Calendar.getInstance();//定义日期实例
        dd.setTime(begin_date);//设置日期起始时间
        while(!dd.getTime().after(end_date)){//判断是否到结束日期
            rangeSet.add(sdf.format(dd.getTime()));
            dd.add(Calendar.MONTH, 1);//进行当前日期月份加1
        }
        return rangeSet;
    }

    /**
     * ============================
     * @Author: hanyuhang
     * @Description:
     * @Date:Created: 2021/10/29
     * @Modify:
     * =============================
     */
    public static String getCurrYearFirst(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return formatDate(currYearFirst);
    }

    /**
     * ============================
     * @Author: hanyuhang
     * @Description:
     * @Date:Created: ${DATE}
     * @Modify:
     * =============================
     */
    public static String getCurrYearLast(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();

        return formatDate(currYearLast);
    }

    /**
     * 格式化日期
     * @param date 日期对象
     * @return String 日期字符串
     */
    public static String formatDate(Date date){
        SimpleDateFormat f = new SimpleDateFormat(DEFAULT_FORMAT);
        String sDate = f.format(date);
        return sDate;
    }

    /**
     * 获取某个月的时间区间.
     * 参数:2018-12-20 12:20:10
     * 返回结果:[2018-12-01,2019-01-01]
     * @param
     * @return
     */
    public static String[] getMonthTimeInterval(String tt) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");//注意月份是MM
        Date date = simpleDateFormat.parse(tt);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH,1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        Date first = calendar.getTime();
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)+1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date end = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        return new String[]{sdf.format(first),sdf.format(end)};
    }

    /**
     * 得到几天前的时间
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateBefore(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

    /**
     * 得到几天前的时间
     *
     * @param beforeDayNum
     * @return
     */
    public static String getBeforeDay(int beforeDayNum) {
        Date dateBefore = getDateBefore(new Date(), beforeDayNum);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(dateBefore);
        return format;
    }

    /**
     *==============================
     * @Author: hanyuhang
     * @Description: 获取最近12个月的月份
     * @Date:Created:
     * @Modify:
     *==============================
     */
    public static List<String> getMonthBefore() {
        // ----
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        //  得到  从当前月开始  往前的十二个月 的时间
        Calendar calendar = Calendar.getInstance();
        //  当前 年和 月
        String nowMonth = sdf.format(calendar.getTime());
        calendar.add(Calendar.MONTH, 0);
        //  12 个 月前 的日期  设置为1号,  月第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, -12);
        Date m3 = calendar.getTime();
        String lastYearMon = sdf.format(m3);

        // 时间线数组
        List<String> lineDates = new ArrayList<>();
        Calendar cnew = Calendar.getInstance();
        for (int i = 1; i <= 12; i++) {
            String time = sdf.format(cnew.getTime());
            lineDates.add(time);
            // 取 i 的 负数
            cnew.add(Calendar.MONTH, -1);
        }
        //  翻转一下时间线
        Collections.reverse(lineDates);
        return lineDates;
    }

    public static List<String> findYearsByNumber(int number) {
        List<String> list = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        calendar.setTime(date);

        int currentYear = calendar.get(Calendar.YEAR);

        for (int i = currentYear - 6; i <= currentYear; i++) {
            list.add(String.valueOf(i));
        }
        return list;
    }

    public static List<String> findMonthByNumber(int number) {
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String[] months = new String[number];

        for (int i = 0; i < number; i++) {
            months[i] = now.minusMonths((number-1) - i).format(formatter);
        }
        return Arrays.asList(months);
    }

    public static List<String> findLastDaysByNumber(int number) {
        String[] days = new String[number];
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (int i = 0; i < number; i++) {
            LocalDate date = LocalDate.now().minusDays((number-1) - i);
            days[i] = date.format(formatter);
        }
        return Arrays.asList(days);
    }

}
